import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/model/FictionChapterData.dart';
import 'package:flutter_app/model/SearchFictionData.dart';
import 'package:flutter_app/novel/FictionContentPage.dart';
import 'package:flutter_app/novel/FictionPageViewModel.dart';
import 'package:provider/provider.dart';

class FictionPage extends StatefulWidget {
  FictionPage({Key key, @required this.fictionData}) : super(key: key);
  final SearchFictionData fictionData;

  @override
  State<StatefulWidget> createState() =>
      _FictionPageState(fictionData: fictionData);
}

class _FictionPageState extends State<FictionPage> {
  _FictionPageState({@required this.fictionData});

  ///上个页面传来的书籍信息
  final SearchFictionData fictionData;

  FictionPageViewModel viewModel = FictionPageViewModel();

  @override
  void initState() {
    super.initState();
    viewModel.getChapter(fictionData.fictionId);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        child: ChangeNotifierProvider(
      create: (_) => viewModel,
      child: Consumer<FictionPageViewModel>(builder: (_, model, __) {
        return CustomScrollView(
          slivers: [
            SliverAppBar(
              leading: IconButton(
                  icon: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.blueGrey,
                  ),
                  onPressed: () {
                    Navigator.pop(context);
                  }),
              title: Text(
                fictionData.title,
                style: TextStyle(color: Colors.blueGrey),
              ),
              expandedHeight: 400.0,
              centerTitle: true,
              pinned: true,
              backgroundColor: Colors.yellow,
              flexibleSpace: FlexibleSpaceBar(
                background: Image.network(
                  fictionData.cover,
                  fit: BoxFit.fill,
                ),
              ),
            ),
            SliverFixedExtentList(
              itemExtent: 50,
              delegate:
                  SliverChildBuilderDelegate((BuildContext context, int index) {
                var item = model.list.isEmpty
                    ? FictionChapterData(title: "", chapterId: "")
                    : model.list[index];
                return GestureDetector(
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (BuildContext context) =>
                                FictionContentPage(chapter: item)));
                  },
                  child: ListTile(
                    title: Text(item.title),
                  ),
                );
              }, childCount: model.list.length),
            )
          ],
        );
      }),
    ));
  }
}
